﻿using Microsoft.AspNetCore.Mvc;
using NET6.WebAPI.Dtos.Tool;
using NET6.WebAPI.Enums;
using NET6.WebAPI.Extensions;
using NET6.WebAPI.Helpers;
using System.Security.Claims;

namespace NET6.WebAPI.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class JwtController : ControllerBase
    {
        private readonly IConfiguration _config;

        public JwtController(IConfiguration config)
        {
            _config = config;
        }

        [HttpGet]
        public IActionResult Get()
        {
            var claims = new[]
            {
                new Claim(ClaimTypes.NameIdentifier, "1"),
                new Claim(ClaimTypes.Name, "hechenyu"),
                new Claim(ClaimTypes.Gender, "男"),
            };

            var jwt = JwtHelper.GetTokenAndRefreshToken(_config, claims);
            return Ok(new HttpResponseDto(HttpResponseCode.TokenSuccess, jwt));
        }

        [HttpGet]
        public IActionResult Refresh(string refreshToken)
        {
            var claims = JwtHelper.ValidateRefreshToken(_config, refreshToken);
            if (!claims.Any()) return Unauthorized();

            claims = claims.Where(it => it.Type.Contains("claims")); // 仅取用户属性

            var jwt = JwtHelper.GetTokenAndRefreshToken(_config, claims);
            return Ok(new HttpResponseDto(HttpResponseCode.TokenSuccess, jwt));
        }
    }
}
